package org.dromara.common.security.utils;

import cn.hutool.crypto.SecureUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * Author: fly
 * Date: 2023/4/17
 **/

public class SecureHelper {

    private static final Logger log = LoggerFactory.getLogger(SecureHelper.class);

    public static boolean checkpw(String plaintext, String hashed) {
        byte[] hashed_bytes;
        byte[] try_bytes;

        String try_pw;
        try {
            try_pw = hashpw(plaintext);
            log.error("-----"+try_pw + " " + hashed);
        } catch (Exception ignore) {
            // 生成密文时错误直接返回false issue#1377@Github
            return false;
        }
        hashed_bytes = hashed.getBytes(StandardCharsets.UTF_8);
        try_bytes = try_pw.getBytes(StandardCharsets.UTF_8);
        if (hashed_bytes.length != try_bytes.length) {
            return false;
        }
        byte ret = 0;
        for (int i = 0; i < try_bytes.length; i++)
            ret |= hashed_bytes[i] ^ try_bytes[i];
        return ret == 0;
    }

    public static String hashpw(String password) {
        return hashpw(password, "wza");
    }

    public static String hashpw(String password, String salt) {
        return SecureUtil.sha256(password + salt);
    }

    public static final void main(String[] args) {
        System.out.println(hashpw("123456"));


    }
}
